package cn.e2win.biz.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.e2win.biz.sys.Dict;
import cn.e2win.biz.sys.SysDictDao;
import cn.e2win.biz.util.DateUtils;
import cn.e2win.biz.util.StringUtils;

public class InitServlet extends HttpServlet {

	static Log logger = LogFactory.getLog(InitServlet.class);


	@Override
	public void service(ServletRequest arg0, ServletResponse arg1)
			throws ServletException, IOException {
		init();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//通过http://127.0.0.1:8080/dms/InitialServlet?type=111这样的方式来请求获取json
		String type = request.getParameter("type");
		//if (type.equals("Function"))
		
		// else if (type.equals("BBB"))
		

	}

	@Override
	public void init() throws ServletException {
		logger.error("start init static data...");
		// 根据业务需要自己定义,这里只是一个例子		
		SysDictDao dictDao = (SysDictDao) getServletBean("sysDictDao");
		
		Dict.initDict(dictDao);

		WebApplicationContext wac = WebApplicationContextUtils
				.getRequiredWebApplicationContext(getServletContext());
		wac.getServletContext().setAttribute("Dict", Dict.Instance);
		wac.getServletContext().setAttribute("DateUtils", DateUtils.Instance);
		wac.getServletContext().setAttribute("StringUtils", StringUtils.Instance);

	}

	// get json
	private void getJson(HttpServletRequest request,
			HttpServletResponse response, List list) {
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		try {
			response.getWriter().print(JSONObject.fromObject(list).toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 获取list或者是某一个属性，自己实现
	// public static String getProperty(){}

	private Object getServletBean(String beanName) {
		WebApplicationContext wac = WebApplicationContextUtils
				.getRequiredWebApplicationContext(getServletContext());
		return wac.getBean(beanName);
	}
}